package com.cuit.bysj.action;

import com.cuit.bysj.entities.User;
import com.cuit.bysj.service.UserService;
import com.cuit.bysj.utils.JsonHelper;
import com.cuit.bysj.utils.Result;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String result;
	private String username;
	private String password;
	private String sex;
	private UserService userService;
	private User user;

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setuserService(UserService userService) {
		this.userService = userService;
	}

	public String login() {
		user = userService.isLogin(username.trim(), password.trim());
		Result<User> Userresult = new Result<User>();

		if (user != null) {
			Userresult.setItem(user);
			Userresult.setSuccess(true);
			Userresult.setMsg("登陆成功！");

			// 判断如果为学生的话生成评价表
			if (user.getStu() != null) {
				userService.initform(user.getStu());
			}
			// 默认评教功能已关闭
			userService.initState();

			ActionContext.getContext().getSession().put("User", user);

		} else {
			Userresult.setSuccess(false);
			Userresult.setMsg("用户名或密码错误");
		}

		result = JsonHelper.getJsonHelper().format(Userresult);

		return "json";
	}

	public String index() {
		return "index";
	}

	public String getcurrentuser() {
		Result<User> Userresult = new Result<User>();

		Userresult.setSuccess(true);
		Userresult.setItem((User) ActionContext.getContext().getSession().get("User"));

		result = JsonHelper.getJsonHelper().format(Userresult);

		return "json";
	}

	public String outlogin() {
		Result<User> Userresult = new Result<User>();

		ActionContext.getContext().getSession().remove("User");
		Userresult.setSuccess(false);

		result = JsonHelper.getJsonHelper().format(Userresult);

		return "json";
	}

	public String updateUser() {
		User user = (User) ActionContext.getContext().getSession().get("User");
		user.setSex(sex);
		user.setPassword(password);
		userService.updateUser(user);

		Result<User> Userresult = new Result<User>();

		Userresult.setSuccess(true);
		Userresult.setMsg("修改个人信息成功！");

		result = JsonHelper.getJsonHelper().format(Userresult);

		return "json";
	}
}
